<?php


namespace app\api;


use think\exception\Handle;
use think\Response;
use Throwable;

class ApiExceptionHandle extends Handle
{
    protected $code;

    protected $msg;

    protected $errorCode;

    /**
     * 接管系统异常处理
     *
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        if ($e instanceof \app\api\BaseException) {
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        } else {
            // todo
            if(false && env('APP_DEBUG')) {
                // 直接打印出来
                return parent::render($request, $e);
            } else {
                // 代码错误
                $this->code = 500;
                $this->msg = "服务器内部错误";
                $this->errorCode = 9999;
                // todo 同时记录错误内容 log
                // $this->recordErrorLog($e);
            }
        }

        return json([
            'msg' => $this->msg,
            'error_code' => $this->errorCode,
            'request_url' => $request->url()
        ], $this->code);
    }

    private function recordErrorLog(Throwable $e)
    {
        \think\facade\Log::error('api-error', [
            $e->getMessage(),
            $e->getFile(),
            $e->getLine(),
            $e->getCode(),
        ]);
    }
}